package com.leesche.zcsp.node.app.v1.controller.operate;

import com.leesche.zcsp.node.app.v1.controller.admin.AppAdminController;
import com.leesche.zcsp.node.app.v1.vo.DeviceInfoVo;
import com.leesche.zcsp.node.app.v1.vo.FactoryDeviceVo;
import com.leesche.zcsp.node.app.v1.vo.PlaceDevicesVo;
import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.utils.NetConfig;
import com.leesche.zcsp.node.utils.PropKit;
import com.leesche.zcsp.node.utils.UUIDGenerateUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.WebUtils;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * Created by kaider on 2016/12/23.
 * 设备模块修订版本
 */
@Controller
@RequestMapping("/app/v1/operate/device")
public class AppDeviceController extends AppAdminController {

    private final static Logger LOGGER = LoggerFactory.getLogger(AppDeviceController.class);
    private final static String payCode = PropKit.use("rqcode.properties").get("payCode1");

    @Autowired
    private PubPlaceService placeService;
    @Autowired
    private PubDeviceService deviceService;
    @Autowired
    private PubDevicetypeService deviceTypeService;
    @Autowired
    private PubDeviceDiscountService deviceDiscountService;
    @Autowired
    private PubDevParamService paramService;
    @Autowired
    private NetService netService;
    @Autowired
    private PubDevGiftStockService stockService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysFirmWareService firmWareService;

    @ResponseBody
    @RequestMapping(value = "/listViewByPlace", method = RequestMethod.POST)
    public Map<String, Object> listViewByPlace(Long placeID, boolean isplace
    ) {
        try {
            Long adminId = getAdminId();
            QueryPubDeviceCondition deviceCondition = new QueryPubDeviceCondition();
            deviceCondition.setAdminId(adminId);
            deviceCondition.setPlaceId(placeID);
            //场地
            PubPlace pubPlace = placeService.selectByPrimaryKey(placeID);
            //场地设备
            Map<String, Object> map = new HashMap<String, Object>();
            List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);

            //在线设备
            List<InfoDeviceDto> online = new ArrayList<InfoDeviceDto>();
            //离线设备
            List<InfoDeviceDto> offline = new ArrayList<InfoDeviceDto>();
            //禁用设备
            List<InfoDeviceDto> disabled = new ArrayList<InfoDeviceDto>();
            //故障设备
            List<InfoDeviceDto> fault = new ArrayList<InfoDeviceDto>();
            if(deviceList.size()>0){
                Map<String, String> deviceOnlines = netService.isOnlineBatch(this.getDeviceNames(deviceList));
                for (InfoDeviceDto deviceDto : deviceList) {
                /*boolean flag = netService.isOnline(deviceDto.getImme());*/
                    if (deviceOnlines.get(deviceDto.getImme()) != null && deviceOnlines.get(deviceDto.getImme()).equalsIgnoreCase("ONLINE")) {
                        deviceDto.setIsOnline(1);
                    } else {
                        deviceDto.setIsOnline(2);
                    }
                    if (deviceDto.getIsOnline().equals(1) && deviceDto.getState().equals(2)) {
                        disabled.add(deviceDto);
                    } else if (deviceDto.getIsOnline().equals(1)) {
                        online.add(deviceDto);
                    } else if (deviceDto.getIsOnline().equals(2)) {
                        offline.add(deviceDto);
                    } else {
                        fault.add(deviceDto);
                    }
                }
            }

            if (isplace) {
                map.put("place", pubPlace);
            }
            map.put("online", online);
            map.put("offline", offline);
            map.put("disabled", disabled);
            map.put("fault", fault);

            //  map.put("placeDevicesList", placeDevicesList);
            return WebResult.success().put("data", map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }


    /**
     * 设备列表
     * @param placeCondition
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/listView", method = RequestMethod.POST)
    public Map<String, Object> listView(
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            Long adminId = getAdminId();
            placeCondition.setAdminId(adminId);
            deviceCondition.setAdminId(adminId);
            //场地
            List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
            //场地设备
            List<PlaceDevicesVo> placeDevicesList = new ArrayList<PlaceDevicesVo>();
            Map<String, Object> map = new HashMap<String, Object>();
            for (PubPlaceDto placeDto : placeList) {
                PlaceDevicesVo vo = new PlaceDevicesVo();
                vo.setPlaceId(placeDto.getPlaceid());
                vo.setPlaceName(placeDto.getAddress());
                deviceCondition.setPlaceId(placeDto.getPlaceid());
                List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);

                //在线设备
                List<InfoDeviceDto> online = new ArrayList<InfoDeviceDto>();
                //离线设备
                List<InfoDeviceDto> offline = new ArrayList<InfoDeviceDto>();
                //禁用设备
                List<InfoDeviceDto> disabled = new ArrayList<InfoDeviceDto>();
                //故障设备
                List<InfoDeviceDto> fault = new ArrayList<InfoDeviceDto>();

                for (InfoDeviceDto deviceDto : deviceList) {
                    boolean flag = netService.isOnline(deviceDto.getImme());
                    if (flag == true) {
                        deviceDto.setIsOnline(1);
                    } else {
                        deviceDto.setIsOnline(2);
                    }
                    if (deviceDto.getIsOnline().equals(1) && deviceDto.getState().equals(2)) {
                        disabled.add(deviceDto);
                    } else if (deviceDto.getIsOnline().equals(1)) {
                        online.add(deviceDto);
                    } else if (deviceDto.getIsOnline().equals(2)) {
                        offline.add(deviceDto);
                    } else {
                        fault.add(deviceDto);
                    }
                    vo.setOnlineList(online);
                    vo.setOfflineList(offline);
                    vo.setDisabledList(disabled);
                    vo.setFaultList(fault);
                }
                placeDevicesList.add(vo);
            }
            map.put("placeDevicesList", placeDevicesList);
            return WebResult.success().put("data", map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设备详情
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editView", method = RequestMethod.POST)
    public Map<String, Object> editView(
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            String businessNo = getBusinessNo();
            InfoDeviceDto dto = deviceService.findInfoDevice(deviceCondition);
            boolean flag = netService.isOnline(dto.getImme());
            if(flag==true){
                dto.setIsOnline(1);
            }else{
                dto.setIsOnline(2);
            }
            dto.setBusinessNo(businessNo);
            return WebResult.success().put("data", dto).toMap();
        } catch (Exception e) {

            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 远程补币
     * @param deviceId
     * @param coin
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addCoin", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceCoin(
            Long deviceId,
            Integer coin
    ) {
        try {
            PubDevice device = getPubDevice(deviceId);
            if (device != null) {
                int deviceTypeId = Integer.parseInt(device.getDevicetypeid().toString());
                boolean flagLine = netService.isOnline(device.getImme());
                if (!flagLine) {
                    return WebResult.failure("设备已离线").toMap();
                } else if (device.getDp() < 15) {
                    return WebResult.failure("设备信号弱,请稍后再试").toMap();
                }

                boolean flagCommand = netService.sendClientBuy(device, 0, coin, NetConfig.PAYTYPE_GAMECOINBU, null);
                if (flagCommand == true) {
                    return WebResult.success().info("指令发送成功").toMap();
                } else {
                    return WebResult.failure("指令发送失败").toMap();
                }
            }
            return WebResult.failure("您没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设备图片
     * @param deviceId
     * @param imageUploadFile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadDeviceImage", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceImage(
            Long deviceId,
            @RequestParam(value = "file", required = false) MultipartFile imageUploadFile
    ) {
        try {
            PubDevice pubDevice = deviceService.selectByPrimaryKey(deviceId);
            if (pubDevice != null) {
                if (imageUploadFile.isEmpty()) {
                    return WebResult.failure("请选择图片").toMap();
                }

                String fileName = imageUploadFile.getOriginalFilename();
                String extName = fileName.substring(fileName.lastIndexOf("."));

                if (!WebUtils.checkIsImage(extName)
                        && !imageUploadFile.getContentType().matches("image.*")) {
                    return WebResult.failure("上传的文件必须是图片!").toMap();
                }

                String hexString = WebUtils.getFileHexString(imageUploadFile.getInputStream());

                boolean flag = false;
                String[] magic = Constants.SYSTEM_IMAGE_MAGICNUMBER;
                for (int i = 0; i < magic.length; i++) {
                    if (magic[i].equals(hexString)) {
                        flag = true;
                        break;
                    }
                }

                if (flag == false) {
                    return WebResult.failure("上传的文件不是图片类型").toMap();
                }

                if (imageUploadFile.getSize() > Constants.SYSTEM_IMAGE_SIZE) {
                    return WebResult.failure("上传的图片实在是太大了,不能超过" + Constants.SYSTEM_IMAGE_SIZE + "M").toMap();
                }

                String imagePath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_DEVICE_DIRECTORY);
                String imageName = UUIDGenerateUtil.generateUUID() + extName;

                File imageFile = new File(imagePath, imageName);

                if (!imageFile.exists()) {
                    imageFile.mkdirs();
                }

                imageUploadFile.transferTo(imageFile);

                pubDevice.setDeviceImageUrl(SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_DEVICE_DIRECTORY + "/" + imageName);
                deviceService.updateByPrimaryKeySelective(pubDevice);
                return WebResult.success().info("上传成功").put("data", pubDevice.getDeviceImageUrl()).toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 多局二维码
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/qrCodeView", method = RequestMethod.POST)
    public Map<String, Object> qrCodeView(
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            PubDevice device = getPubDevice(deviceCondition.getDeviceId());
            if (device != null) {
                Map<String, Object> map = new HashMap<String, Object>();
                String payUrlTemp = PropKit.use("rqcode.properties").get("payCode1");
                String payUrl = payUrlTemp.replace("PAYCODE", device.getMac());
                map.put("payUrl", payUrl);
                return WebResult.success().put("data", map).toMap();
            }
            return WebResult.failure("您没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设置设备套餐
     * @param deviceId
     * @param discountIds
     * @param condition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editDeviceDiscount", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceDiscount(
            Long deviceId,
            Long[] discountIds,
            QueryPubDeviceDiscountCondition condition
    ) {
        try {
            PubDevice device = getPubDevice(deviceId);
            if (device != null) {
                condition.setAdminId(device.getAdminid());
                deviceDiscountService.deleteDeviceDiscount(condition);

                for (Long discountId : discountIds) {
                    PubDeviceDiscount deviceDiscount = new PubDeviceDiscount();
                    deviceDiscount.setDiscountid(discountId);
                    deviceDiscount.setDeviceid(condition.getDeviceId());
                    deviceDiscount.setAdminid(device.getAdminid());
                    deviceDiscountService.insert(deviceDiscount);
                }
                return WebResult.success().toMap();
            }
            return WebResult.failure("您没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设置设备参数
     * @param deviceId
     * @param paramCondition
     * @param devParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateDeviceParam", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceParam(
            Long deviceId,
            QueryPubDevParamCondition paramCondition,
            PubDevParam devParam
    ) {
        try {
            PubDevice device = getPubDevice(deviceId);
            PubDevParam newDevParam = null;
            if (device != null) {
                PubDevParamDto paramDto = paramService.findByCondition(paramCondition);
                if (paramDto != null) {
                    newDevParam = paramService.selectByPrimaryKey(paramDto.getParamid());
                    newDevParam.setAdminid(device.getAdminid());
                    newDevParam.setDeviceid(deviceId);
                    newDevParam.setDevicetypeid(devParam.getDevicetypeid());
                    newDevParam.setParam1(devParam.getParam1());
                    newDevParam.setParam2(devParam.getParam2());
                    newDevParam.setParam3(devParam.getParam3());
                    newDevParam.setParam4(devParam.getParam4());
                    newDevParam.setParam5(devParam.getParam5());
                    newDevParam.setParam6(devParam.getParam6());
                } else {
                    newDevParam = new PubDevParam();
                    newDevParam.setAdminid(device.getAdminid());
                    newDevParam.setDeviceid(deviceId);
                    newDevParam.setDevicetypeid(devParam.getDevicetypeid());
                    newDevParam.setParam1(devParam.getParam1());
                    newDevParam.setParam2(devParam.getParam2());
                    newDevParam.setParam3(devParam.getParam3());
                    newDevParam.setParam4(devParam.getParam4());
                    newDevParam.setParam5(devParam.getParam5());
                    newDevParam.setParam6(devParam.getParam6());
                }
                if (newDevParam.getParamid() != null) {
                    //更新
                    paramService.updateByPrimaryKeySelective(newDevParam);
                } else {
                    //新增
                    paramService.insert(newDevParam);
                }
                return WebResult.success().toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设置设备名称
     * @param deviceId
     * @param deviceName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editName", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceName(
            Long deviceId,
            String deviceName
    ) {
        try {
            PubDevice device = getPubDevice(deviceId);
            if (device != null) {
                device.setDevicename(deviceName);
                deviceService.updateByPrimaryKeySelective(device);
                return WebResult.success().toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设备类型
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deviceTypeView", method = RequestMethod.POST)
    public Map<String, Object> deviceTypeView() {
        try {
            List<PubDevicetypeDto> deviceTypeList = deviceTypeService.findDeviceTypeList();
            return WebResult.success().put("data", deviceTypeList).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设置设备类型
     * @param deviceId
     * @param deviceTypeId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateDeviceType", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceType(
            Long deviceId,
            Long deviceTypeId
    ) {
        try {
            PubDevice device = getPubDevice(deviceId);
            if (device != null) {
                device.setDevicetypeid(deviceTypeId);
                deviceService.updateByPrimaryKeySelective(device);
                return WebResult.success().toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设置设备状态
     * @param deviceId
     * @param isOnline
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateDeviceStatus", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceState(
            Long deviceId,
            Integer isOnline
    ) {
        try {
            PubDevice device = getPubDevice(deviceId);
            if (device != null) {
                if (device.getIsonline() != 1) {
                    return WebResult.failure("设备离线").toMap();
                }
                int deviceTypeId = Integer.parseInt(device.getDevicetypeid().toString());
                if (isOnline == 1) {
                    netService.sendClientStartOrClose(device.getImme(), deviceTypeId, true);
                    device.setState(isOnline);
                } else {
                    netService.sendClientStartOrClose(device.getImme(), deviceTypeId, false);
                    device.setState(isOnline);
                }
                deviceService.updateByPrimaryKeySelective(device);
                return WebResult.success().toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设置设备是否启用优惠码
     * @param deviceId
     * @param disCodeState
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateIsDisCode", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceCouponState(
            Long deviceId,
            Integer disCodeState
    ) {
        try {
            PubDevice device = getPubDevice(deviceId);
            if (device != null) {
                device.setIsdiscode(disCodeState);
                deviceService.updateByPrimaryKeySelective(device);
                return WebResult.success().toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设置设备场地
     * @param deviceId
     * @param placeId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editDevicePlace", method = RequestMethod.POST)
    public Map<String, Object> updateDevicePlace(
            Long deviceId,
            Long placeId
    ) {
        try {
            PubDevice pubDevice = getPubDevice(deviceId);
            if (pubDevice != null) {
                pubDevice.setPlaceid(placeId);
                deviceService.updateByPrimaryKeySelective(pubDevice);
                return WebResult.success().toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 修改SIM流量卡
     * @param deviceId
     * @param simImageUploadFile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateDeviceSIM", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceSIM(
            Long deviceId,
            @RequestParam(value = "file", required = false) MultipartFile simImageUploadFile
    ) {
        try {
            PubDevice pubDevice = deviceService.selectByPrimaryKey(deviceId);
            if (pubDevice != null) {
                if (simImageUploadFile.isEmpty()) {
                    return WebResult.failure("请选择图片").toMap();
                }

                String fileName = simImageUploadFile.getOriginalFilename();
                String extName = fileName.substring(fileName.lastIndexOf("."));

                if (!WebUtils.checkIsImage(extName)
                        && !simImageUploadFile.getContentType().matches("image.*")) {
                    return WebResult.failure("上传的文件必须是图片!").toMap();
                }

                String hexString = WebUtils.getFileHexString(simImageUploadFile.getInputStream());

                boolean flag = false;
                String[] magic = Constants.SYSTEM_IMAGE_MAGICNUMBER;
                for (int i = 0; i < magic.length; i++) {
                    if (magic[i].equals(hexString)) {
                        flag = true;
                        break;
                    }
                }

                if (flag == false) {
                    return WebResult.failure("上传的文件不是图片类型").toMap();
                }

                if (simImageUploadFile.getSize() > Constants.SYSTEM_IMAGE_SIZE) {
                    return WebResult.failure("上传的图片实在是太大了,不能超过" + Constants.SYSTEM_IMAGE_SIZE + "M").toMap();
                }

                String imagePath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_DEVICE_DIRECTORY);
                String imageName = UUIDGenerateUtil.generateUUID() + extName;

                File imageFile = new File(imagePath, imageName);

                if (!imageFile.exists()) {
                    imageFile.mkdirs();
                }

                simImageUploadFile.transferTo(imageFile);

                pubDevice.setSdata5(SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_DEVICE_DIRECTORY + "/" + imageName);
                deviceService.updateByPrimaryKeySelective(pubDevice);
                return WebResult.success().info("上传成功").put("data", pubDevice.getDeviceImageUrl()).toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }


    /**
     * 设备解绑
     * @param deviceId
     * @param deviceDiscountCondition
     * @param statisticsCondition
     * @param stockCondition
     * @param paramCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/unbindDevice", method = RequestMethod.POST)
    public Map<String, Object> updateDeviceBindState(
            Long deviceId,
            QueryPubDeviceDiscountCondition deviceDiscountCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            QueryPubDevGiftStockCondition stockCondition,
            QueryPubDevParamCondition paramCondition
    ) {
        try {
            PubDevice pubDevice = getPubDevice(deviceId);
            if (pubDevice != null) {
                Long adminId = pubDevice.getAdminid();
                deviceDiscountCondition.setAdminId(adminId);
                statisticsCondition.setUserId(adminId);
                stockCondition.setAdminId(adminId);

                //解除设备绑定的礼品
                stockService.deleteDevGiftStock(stockCondition);

                //解除设备绑定的套餐
                deviceDiscountService.deleteDeviceDiscount(deviceDiscountCondition);

                //解除设备绑定的参数
                paramService.deleteDevParam(paramCondition);

                //解除设备关联
                pubDevice.setAdminid(0L);
                pubDevice.setPlaceid(0L);
                pubDevice.setDeviceImageUrl("");
                pubDevice.setDevicename("");
                pubDevice.setIsdiscode(0);
                deviceService.updateByPrimaryKeySelective(pubDevice);

                return WebResult.success().toMap();
            }
            return WebResult.failure("没有权限").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 检测是否注册设备
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkDevice", method = RequestMethod.POST)
    public Map<String, Object> checkDevice(
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            PubDeviceDto dto = deviceService.selectByCondition(deviceCondition);
            PubDevice device = deviceService.selectByPrimaryKey(dto.getDeviceid());

            Long adminId = getAdminId();
            if (device != null) {
                if (device.getAdminid() != null) {
                    if (adminId.equals(device.getAdminid())) {
                        return WebResult.failure("此设备您已经绑定").toMap();
                    } else if (device.getAdminid() != 0 && !adminId.equals(device.getAdminid())) {
                        String error = getUserInfo(device.getAdminid());
                        return WebResult.failure("此设备已被其他用户绑定" + error).toMap();
                    } else {
                        dto.setBusinessNo(getBusinessNo());
                        return WebResult.success().put("data", dto).toMap();
                    }
                } else {
                    dto.setBusinessNo(getBusinessNo());
                    return WebResult.success().put("data", dto).toMap();
                }
            } else {
                return WebResult.failure("设备未注册").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure("无法识别，请使用正确的二维码").toMap();
        }
    }

    /**
     * 设备添加
     * @param device
     * @param discountIds
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addDevice", method = RequestMethod.POST)
    public Map<String, Object> addDevice(
            PubDevice device,
            @RequestParam("discountIds") Long[] discountIds,
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            PubDeviceDto dto = deviceService.findByCondition(deviceCondition);
            Long adminId = getAdminId();
            if (dto == null) {
                return WebResult.failure("未知设备").toMap();
            }
            if (StringUtils.isEmpty(dto.getMac())) {
                return WebResult.failure("设备未绑定").toMap();
            }
            if (dto.getAdminid() != null && dto.getAdminid() > 0) {
                return WebResult.failure("设备已绑定其他帐号").toMap();
            }
            device.setState(1);
            device.setIsdiscode(1);
            device.setAdminid(adminId);
            device.setDeviceid(dto.getDeviceid());
            device.setBindtime(new Date());
            deviceService.updateByPrimaryKeySelective(device);

            for (Long discountId : discountIds) {
                PubDeviceDiscount deviceDiscount = new PubDeviceDiscount();
                deviceDiscount.setDiscountid(discountId);
                deviceDiscount.setDeviceid(device.getDeviceid());
                deviceDiscount.setAdminid(adminId);
                this.deviceDiscountService.insert(deviceDiscount);
            }
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 给工厂用户查询设备列表接口
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchDeviceList", method = RequestMethod.POST)
    public Map<String, Object> searchDeviceList(
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            List<FactoryDeviceVo> voList = deviceService.selectFactoryDeviceVo(deviceCondition);
            String payUrl = PropKit.use("rqcode.properties").get("payCode1");
            List<FactoryDeviceVo> list = new ArrayList<FactoryDeviceVo>();
            for(FactoryDeviceVo vo : voList){
                String payUrlTemp = payUrl.replace("PAYCODE",vo.getMac()).toString();
                vo.setPayUrl(payUrlTemp);
                list.add(vo);
            }
            return WebResult.success().put("data", list).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 给工厂用户查询设备接口
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchDevice", method = RequestMethod.POST)
    public Map<String, Object> searchDevice(
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            FactoryDeviceVo vo = deviceService.selectFactoryDevice(deviceCondition);
            return WebResult.success().put("data", vo).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }


    /**
     * 给工厂用户查询设备接口
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/speed", method = RequestMethod.POST)
    public Map<String, Object> searchDevice(
            Long deviceId
    ) {
        try {
            PubDevice device = getPubDevice(deviceId);
            if (device != null) {
                netService.sendClientGetDeviceInfo(device.getImme(), 1);
                return WebResult.success().info("测试指令发送成功，请等待响应结果!").toMap();
            } else {
                return WebResult.failure("无权限操作此设备").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * fixme
     * 工厂检查设备是否已经被注册
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkFactoryDevice", method = RequestMethod.POST)
    public Map<String, Object> checkFactoryDevice(
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            PubDevice device = deviceService.checkFactoryDevice(deviceCondition);
            if(device != null){
                if(StringUtils.isNotBlank(device.getImme())&&StringUtils.isNoneBlank(deviceCondition.getImme())){
                    return WebResult.failure("设备已经绑定").toMap();
                }
                if(StringUtils.isNotBlank(device.getDeviceshortcode())&&StringUtils.isNoneBlank(deviceCondition.getDeviceshortcode())){
                    return WebResult.failure("此简码已使用").toMap();
                }
                if(StringUtils.isNotBlank(device.getMac())&&StringUtils.isNoneBlank(deviceCondition.getMac())){
                    return WebResult.failure("此支付码已使用").toMap();
                }
                return WebResult.success().toMap();
            }else{
                if(deviceCondition.getImme()!=null){
                    return WebResult.failure("设备未注册").toMap();
                }
                return WebResult.success().toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure("无法识别，请使用正确的二维码").toMap();
        }
    }


    /**
     * 新设备信息含设备固件信息
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deviceInfoView", method = RequestMethod.POST)
    public Map<String, Object> deviceInfoView(
            QueryPubDeviceCondition deviceCondition
    ) {
        try {
            String businessNo = getBusinessNo();
            DeviceInfoVo vo = deviceService.findDeviceInfo(deviceCondition);
            vo.getDto().setBusinessNo(businessNo);
            return WebResult.success().put("data", vo).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 已经发布的固件(按时间倒叙排列)
     * @param condition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sysFirmWareView", method = RequestMethod.POST)
    public Map<String, Object> sysFirmWareView(
            QuerySysFirmWareCondition condition
    ) {
        try {
            List<SysFirmWareDto> dtos = firmWareService.findListsByCondition(condition);
            return WebResult.success().put("data", dtos).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 判断用户是否有权限进行操作
     * @param deviceId
     * @return
     */
    private PubDevice getPubDevice(
            Long deviceId
    ) {
        Long adminId = getAdminId();
        PubDevice device = deviceService.selectByPrimaryKey(deviceId);
        if (device.getAdminid() != null) {
            if (!adminId.equals(device.getAdminid()) && device.getAdminid() != 0) {
                return null;
            } else if (adminId.equals(device.getAdminid())) {
                return device;
            }
        }
        return null;
    }

    /**
     * 获取登录用户的用户名和手机号码
     * @param userId
     * @return
     */
    private String getUserInfo(Long userId) {
        SysUser user = userService.selectByPrimaryKey(userId);
        String username = "";
        String phone = "";
        if (user != null) {
            if (user.getUsername() != null) {
                username = user.getUsername();
            }
            if (user.getMobile() != null) {
                String mobile = user.getMobile();
                phone = mobile.substring(0, mobile.length() - (mobile.substring(3)).length()) + "*****" + mobile.substring(8);
            }
            return "\n 用户名:" + username + " \n 手机号:" + phone;
        } else {
            return "\n 未知异常！";
        }
    }


    private List<String> getDeviceNames(List<InfoDeviceDto> lists) {
        List<String> deviceNames = new ArrayList<String>();
        if (lists != null) {
            for (InfoDeviceDto infoDeviceDto : lists) {
                deviceNames.add(infoDeviceDto.getImme());
            }
        }
        return deviceNames;
    }
}